const express = require('express')
const pool = require('../pool');
const router = express.Router();
const base = 'http://localhost:4010/'

const multer = require('multer');
const  uuid = require('uuid')

const uploadTools = multer({
    storage: multer.diskStorage({ // 该存储方案将会把文件直接存入磁盘
        // destination: (req, file, callback)=>{
        //     callback(null, 'static')
        // },
        filename: (req, file, callback)=>{
            // 通过file，获取原始文件名     huangbo.jpg
            console.log('sss',file)
            let name = file.originalname       
            // 截取源文件的后缀 .jpg  .png  ....
            let ext = name.substr(name.lastIndexOf('.'))
            // 生成一个随机文件名，调用callback返回即可
            let newName = uuid.v4() + ext
            callback(null, newName)
        }
    })
})

router.post('/upload',uploadTools.single('file'),(req,res,next)=>{
    //console.log(req)
    let url = base + req.file.filename
    res.send({code:200,url})
})

router.post('/uploadEssay',(req,res,next)=>{
    console.log(req.body);
    let title  =  req.body.title;
    let count = req.body.count;
    let img = req.body.imgSrc.join();
    let id = req.body.id;
    let date  = new Date();
    pool.query(`insert into essay values(null,?,?,default,?,default,?,?);`,[title,count,img,date,id],(err,r)=>{
        if(err){
            return next(err)
        }
        if(r.length > 0){
            res.send({code:200,msg:'动态发布成功'})
        }else{
            res.send({code:200,msg:'动态发布失败'})
        }
    })
})



module.exports = router;